package com.zdx.yswl.ui.activity;

import java.net.URISyntaxException;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.text.Layout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Projection;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.umeng.analytics.MobclickAgent;
import com.zdx.yswl.R;
import com.zdx.yswl.base.KActivity;
import com.zdx.yswl.tool.DisplayTool;
import com.zdx.yswl.tool.KLog;

public class MapActivity extends KActivity implements OnMarkerClickListener, OnGetGeoCoderResultListener {
	private static final String TAG = MapActivity.class.getSimpleName();
	protected MapView mapView;
	private BaiduMap mBaiduMap;
	private LatLng mLatLng;// 外部传入经纬度参数
	private String  mAddress;// 反编码得到的地址
	protected Marker mMarkerA;
	GeoCoder mSearch = null;
	BitmapDescriptor bitmapDe ;//覆盖物图片 

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);
		Intent intent = getIntent();
		mLatLng = new LatLng(Double.valueOf(intent.getStringExtra("latitude")), Double.valueOf(intent.getStringExtra("longitude"))) ;
		KLog.e(TAG, "-----纬度："+mLatLng.latitude + "-----经度:"+mLatLng.longitude);
		initView();
	}

	private void initView() {
		mapView = (MapView) super.findViewById(R.id.bmapsView);
		super.findViewById(R.id.map_nav_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		Button navBtn = (Button) super.findViewById(R.id.daohang);
		navBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openBd();
			}
		});
		
		mBaiduMap = (BaiduMap) mapView.getMap();
		mBaiduMap.setOnMarkerClickListener(this);

		// 初始化搜索模块，注册事件监听
		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(this);
		mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(mLatLng));
		
		
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		openBd();
		return false;
	}


	@Override
	public void onDestroy() {
		mSearch.destroy();
		mapView.onDestroy();
		super.onDestroy();
		if ( bitmapDe != null) {
			bitmapDe.recycle();
		}
	}
	
	@Override
	public void onPause() {
		mapView.onPause();
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onResume() {
		mapView.onResume();
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public static Intent actionStart(Context context,String latitude, String longitude) {
		Intent intent = new Intent(context, MapActivity.class);
		intent.putExtra("latitude", latitude);
		intent.putExtra("longitude", longitude);
		return intent;
	}

	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return true;
	}

	private void openBd() {
		if (mLatLng == null || mAddress == null) {
			return;
		}
		KLog.e(TAG, "----维度" + mLatLng.latitude + "----经度" + mLatLng.longitude);
		MapActivity.actionMap(MapActivity.this, mLatLng.latitude+"", mLatLng.longitude+"", mAddress, mAddress);
	}
	
	/**
	 * 
	 * @param context
	 * @param latitude 维度
	 * @param longitude 经度
	 * @param address 街道详细地址
	 * @param addressName 公司名字
	 */
	public static void actionMap(Context context, String latitude, String longitude, String address, String addressName) {
		String appName = context.getResources().getString(R.string.app_name);
		try {

			String requestUrl = "intent://map/marker?location=" + latitude + "," + longitude + "&title="//
					+ address + "&content=" + addressName + "&src=" //
					+ appName + "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end"; //
			context.startActivity(Intent.getIntent(requestUrl));

		} catch (BaiduMapAppNotSupportNaviException e) {
			Uri uri = Uri.parse("geo:" + latitude + "," + longitude + "?q=" + addressName);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			context.startActivity(intent);
		} catch (URISyntaxException e) {
			Toast.makeText(context, "手机无地图软件", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onGetGeoCodeResult(GeoCodeResult result) {
	}

	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(this, "抱歉，未能找到结果", Toast.LENGTH_LONG).show();
			return;
		}
		
		mBaiduMap.clear();
		mAddress = result.getAddress();
		//添加一 
		mBaiduMap.addOverlay(new MarkerOptions().position(mLatLng)
				.icon(BitmapDescriptorFactory
				.fromResource(R.drawable.icon_marka)).title(mAddress));
		
		Projection proj =  mBaiduMap.getProjection(); //将经纬度 转换成屏幕坐标
		if (proj != null) {
			Point p = proj. toScreenLocation(mLatLng);
			p.y -= 47;
			LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);
			MarkerOptions markerOptions = new MarkerOptions();
			markerOptions = markerOptions.position(llInfo);
			View view = LayoutInflater.from(this).inflate(R.layout.markoptions, null);
			Button mark = (Button)view.findViewById(R.id.markoption_tv);
			mark.setText(mAddress);
			BitmapDescriptor bitmapDe = getViewBitmap(view);
			//添加二
			markerOptions = markerOptions.icon(bitmapDe);
			mBaiduMap.addOverlay(markerOptions);
		}
		mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(mLatLng));
		
		
	}

	
	 private BitmapDescriptor getViewBitmap(View addViewContent) {

	        addViewContent.setDrawingCacheEnabled(true);
	        addViewContent.measure(
	                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
	                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
	        addViewContent.layout(0, 0,
	                addViewContent.getMeasuredWidth(),
	                addViewContent.getMeasuredHeight());

	        addViewContent.buildDrawingCache();
	        Bitmap cacheBitmap = addViewContent.getDrawingCache();
	        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
	        return BitmapDescriptorFactory.fromBitmap(bitmap);
	    }
}
